<template>
  <div class="outter">
    <!-- 开头的添加搜索功能区 -->
    <div class="buttonsearch">
      <a-button type="primary" @click="addLineVisible = true"
        ><a-icon type="plus-circle" />新增菜品种类</a-button
      >
      <div class="searchout">
        <a-button type="dashed" @click="reset">重置</a-button>
        <a-input-search
          style="width: 88%"
          placeholder="搜索菜品"
          enter-button
          @search="onSearch"
        ></a-input-search>
      </div>
    </div>
    <!-- 父表 -->
    <a-table
      :columns="columns"
      :pagination="{ defaultPageSize: 3, position: 'both' }"
      :data-source="data"
      bordered
      :fixed="true"
      :loading="tableLoading"
      :defaultExpandAllRows="true"
    >
      <!-- 修改名称部分 -->
      <template v-for="col in ['name']" :slot="col" slot-scope="text, record">
        <div :key="col">
          <a-input
            v-if="record.editable && text !== '套餐'"
            style="margin: -5px 0"
            :value="text"
            @change="(e) => handleTchange(e.target.value, record, col)"
          />
          <template v-else>
            {{ text }}
          </template>
        </div>
      </template>
      <!-- 操作方法部分 -->
      <template slot="method" slot-scope="text, record">
        <div class="editable-row-operations">
          <span v-if="record.editable">
            <a-button
              type="primary"
              @click="() => tsave(record)"
              :loading="saveLoading"
              >保存</a-button
            >
            <a-divider type="vertical" />
            <a-button @click="() => tcancel(record)">取消</a-button>
          </span>
          <span v-else>
            <a-button
              :disabled="editingKey !== ''"
              type="primary"
              @click="addfood(record)"
            >
              新增菜品
            </a-button>
            <a-divider type="vertical" />
            <a-button :disabled="editingKey !== ''" @click="() => tedit(record)"
              >修改</a-button
            >
            <a-divider type="vertical" />
            <a-popconfirm
              :disabled="editingKey !== ''"
              title="确定删除吗？"
              @confirm="() => deletet(record)"
            >
              <a-button
                :disabled="editingKey !== ''"
                type="danger"
                :loading="record.deleteLoading"
              >
                删除
              </a-button>
            </a-popconfirm>
          </span>
        </div>
      </template>
      <!-- 上传照片部分 -->
      <template slot="photoUrl" slot-scope="text, record">
        <span v-if="!record.editable">
          <img
            :src="record.photoUrl"
            alt=""
            style="height: 40px; width: 40px; border-radius: 10px"
          />
        </span>
        <span v-else>
          <a-upload
            name="file"
            :multiple="true"
            accept="image/*"
            :data="
              (file) => {
                return { photo: file };
              }
            "
            :action="uploadUrl"
            @change="
              (info) => {
                handleUrl(info, { record: record });
              }
            "
            :show-upload-list="false"
          >
            <a v-if="!addloading" class="uploadimage" href="javascript:;">
              <img
                :src="record.photoUrl"
                alt=""
                style="height: 40px; width: 40px; border-radius: 10px"
              />
              <div class="zhezhao">修改</div>
            </a>
            <div v-else>
              <a-icon type="loading" />
            </div>
          </a-upload>
        </span>
      </template>
      <!-- 子代个数部分 -->
      <span slot="child" slot-scope="text, record">{{
        record.child.length
      }}</span>
      <!-- 嵌套的子表部分 -->
      <a-table
        slot="expandedRowRender"
        slot-scope="record"
        :columns="innerColumns"
        :data-source="record.child"
        :pagination="false"
      >
        <!-- 修改的前三个框 -->
        <template
          v-for="col in ['name', 'price', 'describe']"
          :slot="col"
          slot-scope="text, record"
        >
          <div :key="col">
            <a-input
              v-if="record.editable"
              style="margin: -5px 0"
              :value="text"
              @change="(e) => handleTchange(e.target.value, record, col)"
            />
            <template v-else>
              <div class="espli">{{ text }}</div>
            </template>
          </div>
        </template>
        <template slot="classes" slot-scope="text, record">
          <span v-if="!record.editable">
            {{ record.classes }}
          </span>
          <span v-else>
            <a-button @click="changeOption(record)" type="dashed">{{
              record.classes
            }}</a-button>
          </span>
        </template>
        <template slot="method" slot-scope="text, record">
          <div class="editable-row-operations">
            <span v-if="record.editable">
              <a-button
                @click="() => tsave(record)"
                type="primary"
                :loading="saveLoading"
                >保存</a-button
              >
              <a-divider type="vertical" />
              <a-button @click="() => tcancel(record)">取消</a-button>
            </span>
            <span v-else>
              <a-button
                :disabled="editingKey !== ''"
                @click="() => tedit(record)"
                type="primary"
                >修改</a-button
              >
              <a-divider type="vertical" />
              <a-popconfirm
                title="确定删除吗？"
                @confirm="() => deletet(record)"
                :disabled="editingKey !== ''"
              >
                <a-button
                  :disabled="editingKey !== ''"
                  type="danger"
                  :loading="record.deleteLoading"
                >
                  删除
                </a-button>
              </a-popconfirm>
            </span>
          </div>
        </template>
        <!-- 图片上涨部分 -->
        <template slot="photoUrl" slot-scope="text, record">
          <span v-if="!record.editable">
            <img
              :src="record.photoUrl"
              alt=""
              style="height: 40px; width: 40px; border-radius: 10px"
            />
          </span>
          <span v-else>
            <a-upload
              name="file"
              :multiple="true"
              accept="image/*"
              :data="
                (file) => {
                  return { photo: file };
                }
              "
              :action="uploadUrl"
              @change="
                (info) => {
                  handleUrl(info, { record: record });
                }
              "
              :show-upload-list="false"
            >
              <a v-if="!addloading" class="uploadimage" href="javascript:;">
                <img
                  :src="record.photoUrl"
                  alt=""
                  style="height: 40px; width: 40px; border-radius: 10px"
                />
                <div class="zhezhao">修改</div>
              </a>
              <div v-else>
                <a-icon type="loading" />
              </div>
            </a-upload>
          </span>
        </template>
      </a-table>
    </a-table>
    <!-- 添加桌台弹出框 -->
    <a-modal
      title="添加食品类别"
      :visible="addLineVisible"
      :confirm-loading="confirmLoading"
      @ok="submitForm('lineRuleForm')"
      @cancel="handleCancel"
      okText="确认"
      cancelText="取消"
    >
      <a-form-model
        ref="lineRuleForm"
        :model="lineRuleForm"
        :rules="linerule"
        v-bind="layout"
      >
        <a-form-model-item has-feedback label="类别名称" prop="value">
          <a-input v-model="lineRuleForm.value" autocomplete="off" />
        </a-form-model-item>
        <a-form-model-item has-feedback label="图标" prop="photoUrl">
          <a-upload
            name="avatar"
            list-type="picture-card"
            class="avatar-uploader"
            :show-upload-list="false"
            accept="image/*"
            :data="
              (file) => {
                return { photo: file, name: lineRuleForm.value };
              }
            "
            :action="uploadUrl"
            @change="
              (info) => {
                handleUrl(info, { form: 'lineRuleForm' });
              }
            "
          >
            <img
              v-if="lineRuleForm.photoUrl"
              :src="lineRuleForm.photoUrl"
              alt="avatar"
              style="width: 128px; height: 128px"
            />
            <div v-else>
              <a-icon :type="addloading ? 'loading' : 'plus'" />
              <div class="ant-upload-text">上传</div>
            </div>
          </a-upload>
        </a-form-model-item>
      </a-form-model>
    </a-modal>
    <!-- 添加餐品模块 -->
    <a-modal
      :width="700"
      title="添加餐品"
      :visible="addFoodVisible"
      :confirm-loading="confirmLoading"
      @ok="submitForm('foodRuleForm')"
      @cancel="handleCancel"
      okText="确认"
      cancelText="取消"
      :closable="addFoodClosable"
      :maskClosable="addFoodmaskClosable"
    >
      <a-form-model
        ref="foodRuleForm"
        :model="foodRuleForm"
        :rules="foodrule"
        v-bind="layout"
      >
        <a-form-model-item label="所属类别" prop="name">
          <a-select
            v-if="addFoodmaskClosable"
            v-model="foodRuleForm.name"
            style="width: 120px"
            @select="totalNameChange()"
          >
            <a-select-option
              v-for="item in data"
              :key="item.key"
              :value="item.name"
            >
              {{ item.name }}</a-select-option
            >
          </a-select>
          <span v-else>{{ foodRuleForm.name }}</span>
        </a-form-model-item>
        <a-form-model-item has-feedback label="餐品名称" prop="value">
          <a-input v-model="foodRuleForm.value" autocomplete="off" />
        </a-form-model-item>
        <a-form-model-item has-feedback label="餐品价格" prop="price">
          <a-input v-model="foodRuleForm.price" autocomplete="off" />
        </a-form-model-item>
        <a-form-model-item has-feedback label="餐品描述" prop="describe">
          <a-input v-model="foodRuleForm.describe" autocomplete="off" />
        </a-form-model-item>
        <a-form-model-item has-feedback label="图片" prop="photoUrl">
          <a-upload
            name="avatar"
            list-type="picture-card"
            class="avatar-uploader"
            :show-upload-list="false"
            accept="image/*"
            :data="
              (file) => {
                return { photo: file, name: foodRuleForm.value };
              }
            "
            :action="uploadUrl"
            @change="
              (info) => {
                handleUrl(info, { form: 'foodRuleForm' });
              }
            "
          >
            <img
              v-if="foodRuleForm.photoUrl"
              :src="foodRuleForm.photoUrl"
              alt="avatar"
              style="width: 128px; height: 128px"
            />
            <div v-else>
              <a-icon :type="addloading ? 'loading' : 'plus'" />
              <div class="ant-upload-text">上传</div>
            </div>
          </a-upload>
        </a-form-model-item>
        <a-form-model-item has-feedback label="类别" prop="classes">
          <a-select v-model="foodRuleForm.classes" style="width: 120px">
            <!-- 这里特别针对当选了其他类时就不能显示套餐类别，反之 -->
            <a-select-option v-if="foodRuleForm.name !== '套餐'" value="规格">
              规格
            </a-select-option>
            <a-select-option v-if="foodRuleForm.name !== '套餐'" value="单品">
              单品
            </a-select-option>
            <a-select-option v-if="foodRuleForm.name === '套餐'" value="套餐">
              套餐
            </a-select-option>
          </a-select>
          <a-button
            type="dashed"
            @click="addZu(foodRuleForm.classes)"
            v-if="
              foodRuleForm.classes === '规格' || foodRuleForm.classes === '套餐'
            "
            >增加选项组</a-button
          >
        </a-form-model-item>
        <a-form-model-item
          v-if="foodRuleForm.classes === '规格'"
          has-feedback
          label="选项"
          prop="specifications"
        >
          <div
            v-for="(item, index) in foodRuleForm.specifications"
            :key="index"
            class="specificationsZu"
          >
            <div>
              <span>选项组标题：</span>
              <a-select
                v-model="item.title"
                style="width: 120px"
                @select="guigeChange(item)"
              >
                <a-select-option value="规格"> 规格 </a-select-option>
                <a-select-option value="熟度"> 熟度 </a-select-option>
              </a-select>
              <a-button @click="addXiang(item.option)" type="dashed"
                >增加选项</a-button
              >
            </div>
            <span>默认项：</span>
            <a-radio-group v-model="item.choose" :name="item.title">
              <a-radio
                v-for="(it, imoren) in item.option"
                :value="it.name"
                :key="imoren"
              >
                {{ it.name }}
              </a-radio>
            </a-radio-group>
            <a-divider />
            <div v-for="(i, ixuan) in item.option" :key="ixuan">
              <span class="specifications"
                >选项名称：
                <a-popconfirm
                  v-if="ixuan !== 0"
                  class="deleteXiang"
                  title="确定删除这个选项吗?"
                  ok-text="确定"
                  cancel-text="取消"
                  @confirm="deleteXiangConfirm(item.option, ixuan)"
                  ><a href="#"><a-icon class="smallicon" type="close" /></a
                ></a-popconfirm> </span
              ><a-select
                :value="i.name"
                style="width: 30%"
                @change="
                  (value) => {
                    comboSelect(item, value, i);
                  }
                "
              >
                <a-select-option
                  v-for="(dan, index) in item.itemXuan"
                  :key="index"
                  :value="dan"
                >
                  {{ dan }}
                </a-select-option> </a-select
              ><a-divider type="vertical" /><span
                v-if="item.title !== '熟度' && ixuan !== 0"
                >加价：</span
              ><a-input
                v-if="item.title !== '熟度' && ixuan !== 0"
                placeholder="原价基础加钱"
                class="specificationsInput"
                v-model="i.addprice"
                autocomplete="off"
              />
            </div>
            <a-popconfirm
              class="deleteZu"
              title="确定删除这个选项组吗?"
              ok-text="确定"
              cancel-text="取消"
              @confirm="deleteZuConfirm(foodRuleForm.classes, index)"
              ><a href="#"><a-icon type="close" /></a
            ></a-popconfirm>
          </div>
        </a-form-model-item>
        <a-form-model-item
          v-if="foodRuleForm.classes === '套餐'"
          has-feedback
          label="选项组"
          prop="combo"
        >
          <div
            v-for="(item, index) in foodRuleForm.combo"
            :key="index"
            class="specificationsZu"
          >
            <div>
              <span>选项组标题：</span>
              <a-select
                v-model="item.title"
                style="width: 120px"
                @select="itemXuanChange(item)"
              >
                <a-select-option
                  v-for="item in data"
                  :key="item.key"
                  :value="item.name"
                >
                  {{ item.name }}</a-select-option
                >
              </a-select>
              <a-button @click="addXiang(item.option)" type="dashed"
                >增加选项</a-button
              >
            </div>
            <span>默认项：</span>
            <a-radio-group v-model="item.choose" :name="item.title">
              <a-radio
                v-for="(it, imoren) in item.option"
                :value="it.name"
                :key="imoren"
              >
                {{ it.name }}
              </a-radio>
            </a-radio-group>
            <a-divider />
            <div v-for="(i, ixuan) in item.option" :key="ixuan">
              <span class="specifications"
                >选项名称：
                <a-popconfirm
                  v-if="ixuan !== 0"
                  class="deleteXiang"
                  title="确定删除这个选项吗?"
                  ok-text="确定"
                  cancel-text="取消"
                  @confirm="deleteXiangConfirm(item.option, ixuan)"
                  ><a href="#"><a-icon class="smallicon" type="close" /></a
                ></a-popconfirm> </span
              ><a-select
                :value="i.name"
                style="width: 30%"
                @change="
                  (value) => {
                    comboSelect(item, value, i);
                  }
                "
              >
                <a-select-option
                  v-for="(dan, index) in item.itemXuan"
                  :key="index"
                  :value="dan"
                >
                  {{ dan }}
                </a-select-option> </a-select
              ><a-divider type="vertical" /><span
                v-if="item.title !== '熟度' && ixuan !== 0"
                >加价：</span
              ><a-input
                v-if="item.title !== '熟度' && ixuan !== 0"
                placeholder="原价基础加钱"
                class="specificationsInput"
                v-model="i.addprice"
                autocomplete="off"
              />
            </div>
            <a-popconfirm
              class="deleteZu"
              title="确定删除这个选项组吗?"
              ok-text="确定"
              cancel-text="取消"
              @confirm="deleteZuConfirm(foodRuleForm.classes, index)"
              ><a href="#"><a-icon type="close" /></a
            ></a-popconfirm>
          </div>
        </a-form-model-item>
      </a-form-model>
    </a-modal>
    <OPTION ref="optionDetail" :data="data" :comboMap="comboMap"></OPTION>
    <a-back-top :visibilityHeight="200" />
  </div>
</template>

<script>
//修改时弹出来的窗口我另外写了一个
import OPTION from "@/components/optionDetail";
//上传图片时一个个改图片太麻烦，特地把url拿过来以后就不会忘记改了
import VueConfig from "../../../vue.config.js";
import {
  categoryChange,
  deleteCategory,
  categoryAdd,
  queryItem,
  deleteItem,
  itemChange,
  addItem,
  getAllItem,
} from "@/api/meals";
// 定义四列属性
const columns = [
  {
    title: "菜品种类",
    dataIndex: "name",
    width: "30%",
    align: "center",
    scopedSlots: { customRender: "name" },
  },
  {
    title: "菜品个数",
    dataIndex: "child",
    width: "10%",
    align: "center",
    sorter: (a, b) => a.child - b.child,
    sortDirections: ["descend", "ascend"],
    scopedSlots: { customRender: "child" },
  },
  {
    title: "种类图标",
    dataIndex: "photoUrl",
    width: "20%",
    align: "center",
    ellipsis: true,
    scopedSlots: { customRender: "photoUrl" },
  },
  {
    title: "操作",
    dataIndex: "method",
    align: "center",
    scopedSlots: { customRender: "method" },
  },
];
const innerColumns = [
  {
    title: "菜品名称",
    dataIndex: "name",
    width: "15%",
    align: "center",
    scopedSlots: { customRender: "name" },
  },
  {
    title: "价格",
    dataIndex: "price",
    align: "center",
    width: "10%",
    sorter: (a, b) => a.price - b.price,
    sortDirections: ["descend", "ascend"],
    scopedSlots: { customRender: "price" },
  },
  {
    title: "类别",
    dataIndex: "classes",
    align: "center",
    width: "15%",
    scopedSlots: { customRender: "classes" },
  },
  {
    title: "描述",
    dataIndex: "describe",
    width: "20%",
    align: "center",

    scopedSlots: { customRender: "describe" },
  },
  {
    title: "图片",
    dataIndex: "photoUrl",
    width: "10%",
    scopedSlots: { customRender: "photoUrl" },
    align: "center",
    ellipsis: true,
  },
  {
    title: "操作",
    dataIndex: "method",
    align: "center",
    scopedSlots: { customRender: "method" },
  },
];
// // 初始化插入数据
// const innerData = [];
// for (let i = 0; i < 12; i++) {
//   let size;
//   if (i % 3 == 0) {
//     innerData.push({
//       key: i,
//       id: i,
//       name: `规格${i}`,
//       classes: "规格",
//       price: "3",
//       describe: "超级美味，超级好吃哈哈哈哈",
//       photoUrl: "https://mis-western-restaurant.oss-cn-guangzhou.aliyuncs.com/images/2022/03/17/57ae9abe-6d6e-4b0c-8693-a53d7cb47241.jpg",
//       method: {},

//     });
//   } else if (i % 3 == 1) {
//     innerData.push({
//       key: i,
//       id: i,
//       name: `汉堡${i}`,
//       classes: "单品",
//       price: "3",
//       describe: "超级美味，超级好吃哈哈哈哈",
//       photoUrl: "https://mis-western-restaurant.oss-cn-guangzhou.aliyuncs.com/images/2022/03/17/57ae9abe-6d6e-4b0c-8693-a53d7cb47241.jpg",
//       method: {},
//     });
//   } else {
//     innerData.push({
//       key: i,
//       id: i,
//       name: `套餐${i}`,
//       classes: "套餐",
//       price: "3",
//       describe: "超级美味，超级好吃哈哈哈哈",
//       photoUrl: "https://mis-western-restaurant.oss-cn-guangzhou.aliyuncs.com/images/2022/03/17/57ae9abe-6d6e-4b0c-8693-a53d7cb47241.jpg",
//       method: {},
//     });
//   }
// }
// const data = [];
// for (let i = 0; i < 3; i++) {
//   let size;
//   data.push({
//     key: i,
//     id: i,
//     name: `汉堡${i}`,
//     child: innerData,
//     photoUrl: "https://mis-western-restaurant.oss-cn-guangzhou.aliyuncs.com/images/2022/03/17/57ae9abe-6d6e-4b0c-8693-a53d7cb47241.jpg",
//     method: {},
//   });
// }

export default {
  data() {
    // 添加菜单类别判断
    let validateLineValue = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入名称"));
      } else if (value.length > 6) {
        callback(new Error("名称不应该过长"));
      } else if (
        this.data.some((item) => {
          return item.name == value;
        })
      ) {
        callback(new Error("已有该类别名称"));
      } else {
        callback();
      }
    };
    let validateFoodValue = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入名称"));
      } else if (value.length > 7) {
        callback(new Error("名称不应该过长"));
      } else if (
        this.data.some((item) => {
          return item.child.some((i) => {
            if (i.name === value) {
              return true;
            }
          });
        })
      ) {
        callback(new Error("已有该菜品名称"));
      } else {
        callback();
      }
    };
    let validateFoodPrice = (rule, value, callback) => {
      if (!/^\d+$/.test(value)) {
        callback(new Error("价格必须为正纯数字"));
      } else {
        callback();
      }
    };
    //上传弹出框图片判断-共享
    let validatephotoUrl = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请上传图片"));
      } else {
        callback();
      }
    };
    let validatespecifications = (rule, value, callback) => {
      if (this.foodRuleForm.classes !== "规格") {
        callback();
      } else {
        console.log(value);
        let fmap = new Map();
        value.map((item) => {
          let chooseOrNO = false;
          if (item.title === "" || item.choose === "") {
            callback(new Error("不应有选项组标题为空或未选默认项"));
          }
          if (fmap.has(item.title)) {
            callback(new Error("不同选项组标题不可相同"));
          } else {
            fmap.set(item.title, "");
          }
          let map = new Map();
          item.option.map((i) => {
            if (i.name === "" || i.addprice === "") {
              callback(new Error("不应有选项或加价为空"));
            }
            if (!/^\d+$/.test(i.addprice)) {
              callback(new Error("加价必须为正纯数字"));
            }
            if (map.has(i.name)) {
              callback(new Error("同一个选项组不应有相同选项"));
            } else {
              map.set(i.name, "");
            }
            if (i.name === item.choose) {
              chooseOrNO = true;
            }
          });
          if (chooseOrNO === false) {
            callback(new Error("请选择默认项"));
          }
        });
        callback();
      }
    };
    let validatecombo = (rule, value, callback) => {
      if (this.foodRuleForm.classes !== "套餐") {
        callback();
      } else {
        console.log(value);
        let fmap = new Map();
        value.map((item) => {
          if (item.title === "" || item.choose === "") {
            callback(new Error("不应有选项组标题为空或未选默认项"));
          }
          if (fmap.has(item.title)) {
            callback(new Error("不同选项组标题不可相同"));
          } else {
            fmap.set(item.title, "");
          }
          let map = new Map();
          item.option.map((i) => {
            if (i.name === "" || i.addprice === "") {
              callback(new Error("不应有选项或加价为空"));
            }
            if (!/^\d+$/.test(i.addprice)) {
              callback(new Error("加价必须为正纯数字"));
            }
            // if(map.has(i.name)){
            //    callback(new Error("同一个选项组不应有相同选项"));
            // }else{
            //   map.set(i.name,"")
            // }
          });
        });
        callback();
      }
    };
    return {
      //保存时的按钮loading
      saveLoading: false,
      // 添加食品mask是否能点击，这里主要是当新增菜类时需要马上新增菜，否则都不增
      addFoodmaskClosable: true,
      addFoodClosable: true,
      //菜类form
      lineRuleForm: {
        value: "",
        photoUrl: "",
      },
      //添加食品的表单
      foodRuleForm: {
        name: "",
        value: "",
        price: "",
        describe: "",
        classes: "单品",
        photoUrl: "",
        specifications: [
          {
            title: "规格",
            choose: "中份",
            itemXuan: ["大份", "中份", "小份"],
            option: [
              {
                name: "小份",
                addprice: 0,
              },
              {
                name: "中份",
                addprice: 1,
              },
              {
                name: "大份",
                addprice: 2,
              },
            ],
          },
          {
            title: "熟度",
            choose: "全熟",
            itemXuan: ["全熟", "七分熟", "五分熟"],
            option: [
              {
                name: "全熟",
                addprice: 0,
              },
              {
                name: "七分熟",
                addprice: 0,
              },
            ],
          },
        ],

        combo: [
          {
            title: "",
            choose: "",
            itemXuan: [],
            option: [
              {
                name: "",
                addprice: 0,
              },
              {
                name: "",
                addprice: 10,
              },
            ],
          },
          {
            title: "",
            choose: "",
            itemXuan: [],
            option: [
              {
                name: "",
                addprice: 0,
              },
              {
                name: "",
                addprice: 4,
              },
            ],
          },
        ],
      },
      //菜类form规则
      linerule: {
        value: [
          { required: true, validator: validateLineValue, trigger: "change" },
        ],
        photoUrl: [
          { required: true, validator: validatephotoUrl, trigger: "blur" },
        ],
      },
      foodrule: {
        value: [
          { required: true, validator: validateFoodValue, trigger: "change" },
        ],
        price: [
          { required: true, validator: validateFoodPrice, trigger: "change" },
        ],
        describe: [{ required: true, trigger: "change" }],
        photoUrl: [
          { required: true, validator: validatephotoUrl, trigger: "blur" },
        ],
        specifications: [
          {
            required: true,
            validator: validatespecifications,
            trigger: "blur",
          },
        ],
        combo: [{ required: true, validator: validatecombo, trigger: "blur" }],
      },
      //弹出框布局
      layout: {
        labelCol: { span: 4 },
        wrapperCol: { span: 14 },
      },
      //上传弹出框图片loading-共享
      addloading: false,
      //添加菜类框是否可见
      addLineVisible: false,
      //添加食物类框是否可见
      addFoodVisible: false,
      //表格Loading
      tableLoading: true,

      //确认提交表单loading-共享
      confirmLoading: false,

      //表格所需
      data: [{ child: [{ key: 1 }], key: 2 }],
      columns,
      innerColumns,
      //现在在修改的key
      editingKey: "",
      //弹出框的图片src-共享
      imageUrl: "",
      //上传地址
      uploadUrl: "",
      //取消时缓存地址
      cachedata: [],
      //比如item对应单品，combo对应套餐
      classesMap: new Map(),
      //比如肉类对应肉类下的数组
      comboMap: new Map(),
    };
  },
  watch: {
    //监控当比如把增加的那个title从肉类改成套餐时也要把底下的类别改位套餐
    foodRuleForm: {
      handler(val, oldVal) {
        if (val.name === "套餐") {
          if (val.classes !== "套餐") {
            this.$message.warn("套餐类别的类别必须为套餐");
          }
          val.classes = "套餐";
        }
      },
      deep: true,
    },
  },
  components: { OPTION },
  created() {
    //拿到表的数据
    this.getTable();
    this.$notification.success({
      message: "温馨提示",
      description: "每行菜类左侧的加号可以点击展开",
      duration: 10,
    });
    //把Vue脚手架配置的url用于这里上传的地方
    this.uploadUrl = "https://miswestrestaurant.xyz/test";
    //先把map弄好等会拿数据直接用
    this.classesMap.set("单品", "item");
    this.classesMap.set("套餐", "combo");
    this.classesMap.set("规格", "size");
  },

  methods: {
    //新增时选肉类会把类别变为单品，避免肉类可以加套餐的情况
    totalNameChange() {
      if (this.foodRuleForm.name !== "套餐") {
        this.foodRuleForm.classes = "单品";
      } else {
        this.foodRuleForm.classes = "套餐";
      }
    },
    //毫无疑问，这里写死了不太好，当选项组选了规格或者熟度以后，底下每个Item选择有所不同
    guigeChange(item) {
      if (item.title === "规格") {
        item.itemXuan = ["大份", "中份", "小份"];
      } else {
        item.itemXuan = ["全熟", "七分熟", "五分熟"];
      }
      item.option.map((i) => {
        i.name = "";
      });
    },
    //上面是规格的，这里是套餐的，比如点了选项组标题点了肉类，从map拿到肉类有的item数组
    itemXuanChange(item) {
      item.itemXuan = this.comboMap.get(item.title);
      //比如选了肉类以后选项组Item为其他类也是可以提交的，那就完了
      item.option.map((i) => {
        i.name = "";
      });
    },
    //后端给的数据不符合要求，我在这里做了一系列加工处理，当然其他接口发过去时还要再次处理所以比较麻烦，最好一次定义好
    loadData(data) {
      data.map((item) => {
        item.key = item.categoryName;
        item.name = item.categoryName;
        item.deleteLoading = false;
        item.method = {};
        let arr = [];
        item.child.map((i) => {
          arr.push(i.itemName);
          i.key = i.itemName;
          i.name = i.itemName;
          i.describe = i.introduction;
          i.deleteLoading = false;
          i.method = {};
          switch (i.classes) {
            case "item":
              i.classes = "单品";
              break;
            case "combo":
              i.classes = "套餐";
              break;
            case "size":
              i.classes = "规格";
              break;
          }
        });
        this.comboMap.set(item.name, arr);
      });
      data.map((item) => {
        item.child.map((it) => {
          it.combo.map((i) => {
            i.itemXuan = this.comboMap.get(i.title);
            i.option.map((smallI) => {
              smallI.name = smallI.name.slice(0, -3);
            });
          });
          it.specifications.map((i) => {
            if (i.title === "规格") {
              i.itemXuan = ["大份", "中份", "小份"];
            } else {
              i.itemXuan = ["全熟", "七分熟", "五分熟"];
            }
          });
        });
      });
      this.data = data;
      this.refreshCachedata();
      this.tableLoading = false;
    },
    //主要是为了把loadData共享出来，查询时也可以用
    getTable() {
      this.tableLoading = true;
      getAllItem().then((res) => {
        this.loadData(res.data);
      });
    },
    //取消时cachedata就会回去，如果修改成功这里则就会刷新缓存数据
    refreshCachedata() {
      this.cachedata = JSON.parse(JSON.stringify(this.data));
    },
    //修改的四个关键方法
    handleTchange(value, record, column) {
      //newData只是一个临时存放点，关键在于刺激v-if进行判断
      const newData = [...this.data];
      record[column] = value;
      this.data = newData;
    },
    tedit(record) {
      //newData只是一个临时存放点，关键在于刺激v-if进行判断
      const newData = [...this.data];
      this.editingKey = record.key;
      record.editable = true;
      this.data = newData;
    },
    // 点击确定修改时要判断很多东西再发
    tsave(record) {
      const newData = [...this.data];
      let tarr = Object.values(record);
      let message = "";
      for (let i = 0; i < tarr.length; i++) {
        if (tarr[i] === "") {
          console.log(tarr);
          message = "不可有修改项为空！";
          break;
        }
        if (i == 0) {
          if (!record.hasOwnProperty("price")) {
            newData.map((item) => {
              if (item.name === record.name && item.key !== record.key) {
                message = "第一项名称不可重复！";
              }
              if (record.name.length > 9) {
                message = "名称不应该过长";
              }
            });
          } else {
            newData.map((item) => {
              item.child.map((i) => {
                if (i.name === record.name && i.key !== record.key) {
                  message = "第一项名称不可重复！";
                }
                if (record.name.length > 9) {
                  message = "名称不应该过长";
                }
              });
            });
          }
          if (record.hasOwnProperty("price") && !/^\d+$/.test(record.price)) {
            message = "价格不可为负数且必须为数字！";
          }
        }
      }
      //如果有问题
      if (message != "") {
        this.$message.warn(message);
        return;
      }
      //人员管理那里用的是This.editkey,但其实record就可以用
      if (record.categoryName) {
        let leiquery = {
          categoryNo: record.categoryNo,
          categoryName: record.name,
          photoUrl: record.photoUrl,
        };
        console.log(leiquery);
        this.changeShare(categoryChange, leiquery, record, newData);
      } else {
        let Danquery = {
          price: parseInt(record.price),
          introduction: record.introduction,
          itemName: record.name,
          itemNo: record.itemNo,
          photoUrl: record.photoUrl,
          classes:
            record.classes === "单品"
              ? "item"
              : record.classes === "套餐"
              ? "combo"
              : "size",
          itemList:
            record.classes === "单品"
              ? []
              : record.classes === "套餐"
              ? record.combo
              : record.specifications,
        };
        console.log(Danquery);
        this.changeShare(itemChange, Danquery, record, newData);
      }
    },
    //change接口共同的代码
    changeShare(func, query, record, newData) {
      this.saveLoading = true;
      func(query).then((res) => {
        this.saveLoading = false;
        if (res.code === 200) {
          this.$message.success("修改成功");
          delete record.editable;
          this.data = newData;
          this.refreshCachedata();
          this.editingKey = "";
        }
      });
    },
    tcancel(record) {
      //不管是[...this.cachedata]还是object.assign整个付过去都会是浅拷贝，我这个效率最低但最省事
      this.editingKey = "";
      delete record.editable;
      this.data = JSON.parse(JSON.stringify(this.cachedata));
    },
    //处理上传事务
    handleUrl(info, obj) {
      this.addloading = true;
      if (info.file.status === "done") {
        // record则为修改，this.RuleForm则为新增
        if (obj.record) obj.record.photoUrl = info.file.response;
        else this[obj.form].photoUrl = info.file.response;
        this.$message.success(`${info.file.name} 上传成功`);
        this.addloading = false;
      } else if (info.file.status === "error") {
        this.$message.error(`${info.file.name} 上传失败.`);
        this.addloading = false;
      }
    },

    //提交表单时
    submitForm(formName) {
      let thing;
      let data = [];
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.confirmLoading = true;
          if (formName === "lineRuleForm") {
            this.addLineVisible = false;
            this.confirmLoading = false;
            thing = {
              key: this.lineRuleForm.value,
              id: this.lineRuleForm.value,
              name: this.lineRuleForm.value,
              categoryName: this.lineRuleForm.value,
              child: [],
              photoUrl: this.lineRuleForm.photoUrl,
            };
            data = this.data;
            // data.push(thing);
            //添加食品种类时一定要添加单品，否则会有问题
            this.addfood({ name: this.lineRuleForm.value }, true);
          } else {
            let query = {
              categoryName: this.foodRuleForm.name,
              itemName: this.foodRuleForm.value,
              price: parseInt(this.foodRuleForm.price),
              introduction: this.foodRuleForm.describe,
              photoUrl: this.foodRuleForm.photoUrl,
              classes: this.classesMap.get(this.foodRuleForm.classes),
              itemList:
                this.foodRuleForm.classes === "单品"
                  ? []
                  : this.foodRuleForm.classes === "套餐"
                  ? this.foodRuleForm.combo
                  : this.foodRuleForm.specifications,
            };
            if (this.addFoodmaskClosable === false) {
              //看看是不是所需要的添加类别时附带的添加食品
              console.log({
                photoUrl: this.lineRuleForm.photoUrl,
                categoryName: this.lineRuleForm.value,
              });
              categoryAdd({
                photoUrl: this.lineRuleForm.photoUrl,
                categoryName: this.lineRuleForm.value,
              });
            }
            setTimeout(() => {
              console.log(query);
              addItem(query).then((res) => {
                if(res.code===200){
                  this.getTable();
                this.addFoodmaskClosable = true;
                this.addFoodClosable = true;
                this.$message.success("默认选项功能暂不可用，敬请期待");
                this.$message.success("成功添加");
                this.confirmLoading = false;
                this.addLineVisible = false;
                this.addFoodVisible = false;
                if (this.$refs["foodRuleForm"]) {
                  this.$refs["foodRuleForm"].resetFields();
                }
                if (this.$refs["lineRuleForm"]) {
                  this.$refs["lineRuleForm"].resetFields();
                }
                }
              });
              // thing = {
              //   key: this.foodRuleForm.value,
              //   id: this.foodRuleForm.value,
              //   name: this.foodRuleForm.value,
              //   price: this.foodRuleForm.price,
              //   describe: this.foodRuleForm.describe,
              //   photoUrl: this.foodRuleForm.photoUrl,
              //   classes: this.foodRuleForm.classes,
              //   combo: this.foodRuleForm.combo,
              //   specifications: this.foodRuleForm.specifications,
              // };
              // this.data.some((item) => {
              //   if (item.name === this.foodRuleForm.name) {
              //     data = item.child;
              //     console.log(item.name);
              //     return true;
              //   }
              // });
            }, 1);
          }
        } else {
          console.log("添加失败");
          return false;
        }
      });
    },

    addfood(record, close) {
      this.foodRuleForm.name = record.name;
      this.addFoodVisible = true;
      //针对添加食品类别的if
      if (close) {
        this.addFoodmaskClosable = false;
        this.addFoodClosable = false;
      }
    },

    //两个弹出框的取消都是这个
    handleCancel() {
      this.addLineVisible = false;
      this.addFoodVisible = false;
      if (this.$refs["foodRuleForm"]) {
        this.$refs["foodRuleForm"].resetFields();
      }
      if (this.$refs["lineRuleForm"]) {
        this.$refs["lineRuleForm"].resetFields();
      }
    },
    //搜索
    onSearch(resu) {
      this.tableLoading = true;
      queryItem({ itemName: resu }).then((resp) => {
        this.tableLoading = false;
        if (resp.code === 500) {
          return;
        } else {
          this.loadData(resp.data);
        }
      });
    },
    //点击重置按钮时
    reset() {
      this.getTable();
    },
    //点击删除按钮时
    delete() {},
    deleteZuConfirm(name, index) {
      if (name == "套餐") name = "combo";
      else name = "specifications";
      if (this.foodRuleForm[name].length === 1) {
        this.$message.warn("至少要有一个选项组");
      } else {
        this.foodRuleForm[name].splice(index, 1);
        this.$message.success("成功删除");
      }
    },
    deleteXiangConfirm(option, index) {
      if (option.length === 2) {
        this.$message.warn("至少要有2个选项");
      } else {
        option.splice(index, 1);
        this.$message.success("成功删除");
      }
    },
    addZu(name) {
      if (name == "套餐") name = "combo";
      else name = "specifications";
      this.foodRuleForm[name].push({
        title: "",
        choose: "",
        itemXuan: [],
        option: [
          {
            name: "",
            addprice: 0,
          },
          {
            name: "",
            addprice: 0,
          },
        ],
      });
      this.$message.success("成功添加,请向下划");
    },
    addXiang(option) {
      option.push({
        name: "",
        addprice: 0,
      });
      this.$message.success("成功添加,请向下划");
    },
    deletet(record) {
      record.deleteLoading = true;
      if (record.categoryName) {
        deleteCategory({ categoryName: record.categoryName }).then((res) => {
          record.deleteLoading = false;
          if (res.code === 200) {
            this.$message.success("成功删除");
            this.getTable();
          }
        });
      } else {
        deleteItem({ itemNo: record.itemNo }).then((res) => {
          record.deleteLoading = false;
          if (res.code === 200) {
            this.$message.success("成功删除");
            this.getTable();
          }
        });
      }
    },
    comboSelect(item, value, i) {
      let flag = item.option.some((item) => {
        if (item.name === value) {
          return true;
        } else {
          return false;
        }
      });
      if (flag) {
        this.$message.warn("该选项组已经有该选项");
      } else {
        item.choose = value;
        i.name = value;
      }
    },
    //修改
    changeOption(record) {
      this.$refs.optionDetail.show(record);
      console.log(record);
    },
  },
};
</script>

<style scoped>
.ant-back-top-inner {
  background-color: rgb(44, 44, 44);
  padding: 5px;
  border-radius: 15px;
  color: white;
}
.outter {
  padding: 20px 10px;
}
.bottonheader {
  widows: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}
.buttons {
  width: 30%;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.nima {
  width: 100%;
  height: 420px;
  background: rgb(217, 220, 223);
}

.editable-row-operations a {
  margin-right: 8px;
}
.buttonsearch {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-direction: row;
  margin-bottom: 25px;
}
.uploadimage {
  font-size: 1px;
  position: relative;
  display: block;
  /* transition: all 1s; */
}
.zhezhao {
  opacity: 0.6;
  background-color: rgb(95, 74, 74);
  transition: all 0.5s;
  color: aliceblue;
  top: 0;
  position: absolute;
  width: 40px;
  text-align: center;
  line-height: 40px;
  border-radius: 10px;
}
.searchout {
  width: 50%;
}

.avatar-uploader > .ant-upload {
  width: 128px;
  height: 128px;
}
.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}
.specificationsInput {
  width: 30%;
}
.specificationsZu {
  background-color: rgb(245, 245, 245);
  padding: 15px;
  border-radius: 10px;
  margin-bottom: 5px;
  width: 130%;
  position: relative;
}
.deleteZu {
  position: absolute;
  top: 1px;
  right: 10px;
}

.specifications {
  position: relative;
}
.deleteXiang {
  position: absolute;
  top: -20px;
  left: -9px;
}
.smallicon {
  font-size: 10px;
}
.comboSelect {
  width: 20%;
}
.espli {
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 1;
  width: 100%;
  -webkit-box-orient: vertical;
}
</style>
